/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.keepalive;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.logos.common.daemon.AbsWorkService;

/**
 * @author Young Ken
 * 使用时需在AndroidManifest中注册
 * 启动锁屏的保活服务
 */

public class ScreenLockService extends AbsWorkService {

    /**
     * 开启时请先设置此变量为false 否则开启失败
     * 关闭时设置此变量为true 然后调用静态方法关闭该服务
     */
    public static boolean sShouldStopService;
    BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
        @SuppressWarnings("deprecation")
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Intent lockIntent = new Intent(context, LockScreenActivity.class);
                lockIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(lockIntent);
            }
        }
    };

    public ScreenLockService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter screenOffFilter = new IntentFilter();
        screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
        screenOffFilter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenOffReceiver, screenOffFilter);
    }

    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        return sShouldStopService;
    }

    @Override
    public void startWork(Intent intent, int flags, int startId) {

    }

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
    }

    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {
        return null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent, Void alwaysNull) {
        return null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenOffReceiver);
    }

    /**
     * 停止服务且停止进程守护
     */
    public static void stopService() {
        cancelJobAlarmSub();
    }

}
